var enterpriseRecordCtrl = new XFApp.client();
Array.prototype.remove=function(dx)
{
    if(isNaN(dx)||dx>this.length){return false;}
    for(var i=0,n=0;i<this.length;i++)
    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
}
XFApp.client.prototype.enterpriseRecord = {
	logi: function(msg){
		console.log(msg);
	},
	enterprisePage: '',
	shopPage: '',
	histroyPage: '',
	editId: '',
	attachArr: new Array(),
	attachType: '',
	attachCode: '',
	enterpriseList: '',
	successCode : "10000",
	loadingDialog: {},
	//网店信息数组
	shops: new Array(),
	urlItems : {
		submitEnterpriseRecordURL: basePath + '/userCenter/enterpriseRecord/save',//提交企业备案
		saveShopUrl: basePath + '/userCenter/enterpriseRecord/saveShops',//提交网店信息
		saveEnterpriseRecordURL: basePath + '/userCenter/enterpriseRecord/saveEnterpriseRecord',//暂存企业备案
		queryEnterprisePageURL: basePath + '/userCenter/enterpriseRecord/selectPage',//查询企业列表数据
		queryShoplistByEnterprisePageURL: basePath + '/userCenter/enterpriseRecord/selectShopPage',//查询企业网店列表数据
		submitToHGURL: basePath + '/userCenter/enterpriseRecord/submit',//提交到通关平台
		queryEnterDetailURL: basePath + '/userCenter/enterpriseRecord/selectDetail',//查询企业详情
		uploadUrl: basePath + '/userCenter/enterpriseAttach/saveAttach',//上传企业附件
		deleteAttachUrl: basePath + '/userCenter/enterpriseAttach/deleteAttach',//删除企业附件
		getAttachByEnterUrl: basePath + '/userCenter/enterpriseAttach/selectAttach'
	},
	initView: function(){
		var _this = this;
		_this.initUploadPlugin();
		_this.queryEnterprisePage();
		_this.enterFormValidate();
		_this.initCostumerCodeSelect();
	},
	initCostumerCodeSelect: function(){
		$("#customSelect").bsSuggest({
			idField: "dictCode",
			keyField: "dictName",
			effectiveFields :["dictCode","dictName"],
			effectiveFieldsAlias:{dictCode:"编码",dictName:"名称"},
	       data: {
	           'value':customerCodes,
	       }
	   }).on('onSetSelectValue', function (e, keyword) {
		   $("#customscodetype").val(keyword.id);
	    });
		customscodeUtil.setDefaultCustom("customSelect",pspName);
	},
	//加载企业列表
	queryEnterprisePage: function(){
		_this = this;
		var params = {};
		if(!!_this.enterprisePage){
			_this.enterprisePage.page("remote",0,params);
		}else{
			_this.enterprisePage = $("#enterprisePage").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryEnterprisePageURL,
			        params: {},
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		_this.enterpriseList = pageResult.itemList;
			        		$("#enterpriseGrid").html($("#enterpriseDataTmpl").render(pageResult.itemList));
			        	}else{
			        		  window.webDialogUtil.alert("提示",data.msg);
			        	}
			        },
			        error : function(){
			      	  window.webDialogUtil.alert("提示",data.msg);
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	/**
	 * 加载企业对应的网店列表
	 */
	queryShoplistByEnterprise: function(id){
		_this = this;
		var params = {enterpiseId: id};
		if(!!_this.shopPage){
			_this.shopPage.page("remote",0,params);
		}else{
			_this.shopPage = $("#shopPage").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryShoplistByEnterprisePageURL,
			        params: {enterpiseId: id},
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;

			        		$("#shopGrid").html($("#shopDataTmpl").render(pageResult.itemList));
			        	}else{
			        		  window.webDialogUtil.alert("提示",data.msg);
			        	}
			        },
			        error : function(){
			      	  window.webDialogUtil.alert("提示",data.msg);
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	submitEnterprise: function(){
		var _this = this;
		if(!$("#enterpriseForm").validate().form()){
			return;
		}
		if(!_this.editId && _this.attachArr.length == 0){
			window.webDialogUtil.alert("提示","请上传企业附件");
			return;
		}
		//是否选择了企业类型或者服务类型
		var isChooseType = false;
		$("#enterpriseForm input[type='checkbox']").each(function(index,el){
			if(el.checked == true){
				isChooseType = true;
			}
		});
		if(!isChooseType){
			window.webDialogUtil.alert("提示","请选择企业类型或服务类型");
			return;
		}
		var enterpriseData = _this.getEnterpriseFormData();

		_this.doSubmitEnter(enterpriseData);
		_this.logi(JSON.stringify(enterpriseData));
	},
	//提交到通关平台
	submitToHG: function(id,type){
		var _this = this;
		_this.loadingDialog = webDialogUtil.loading('正在提交，请稍后...');
		$.ajax({
            type:"POST",
            url:_this.urlItems.submitToHGURL,
            dataType:"json",
            data:{id:id,modifymark:type},
            success:function(data){
                if (data.code == _this.successCode) {
                	window.webDialogUtil.alert("提示","提交成功");
					_this.loadingDialog.close();
					_this.queryEnterprisePage();
                }else{
                	window.webDialogUtil.alert("提示",data.msg);
            		_this.loadingDialog.close();
                }
            },
            error: function(){

                window.webDialogUtil.alert("提示","操作失败");
            	_this.loadingDialog.close();
            }
        });
	},
	doSubmitEnter: function(data){
		var _this = this;
		_this.loadingDialog = webDialogUtil.loading('正在暂存，请稍后...');
		//基于ajaxfileUpload.js实现
		data.id = _this.editId;
		var attachids = "";
		for(var i = 0; i < _this.attachArr.length ; i ++){
			attachids += _this.attachArr[i].id + ','
		}
		data.attachIds = attachids.substring(0,attachids.length-1);
		$.ajax({
			url : _this.urlItems.submitEnterpriseRecordURL,
			secureuri : false,
			data: data,
			dataType : 'json',
			success : function(data) {
				_this.loadingDialog.close();
				if (data.code == _this.successCode) {
					if(data.result.id && _this.shops.length > 0){
						_this.queryEnterprisePage();
						_this.submitShopData(data.result.id);
					}else{
						window.webDialogUtil.alert("提示","暂存成功");
						_this.queryEnterprisePage();
						//_this.refreshEnterForm();


					}

				} else {
					window.webDialogUtil.alert("提示",data.msg);

				}

			},
			error : function(data, status, e){
				window.webDialogUtil.alert("提示",data.msg);
				_this.loadingDialog.close();
			}
		});
	},
	/**
	 * 提交店铺数据
	 */
	submitShopData: function(enterpriseId){
		var _this = this;
		for(var i = 0 ; i < _this.shops.length; i ++){
			_this.shops[i].enterpiseId = enterpriseId;
		}
		$.ajax({
            type:"POST",
            url:_this.urlItems.saveShopUrl,
            dataType:"json",
            contentType:"application/json",
            data:JSON.stringify(_this.shops),
            success:function(data){
                if (data.code == _this.successCode) {
                	window.webDialogUtil.alert("提示","暂存成功");
					_this.loadingDialog.close();
					_this.refreshEnterForm();
                }
            }
        });
	},
	/**
	 * 获取企业备案的表单数据
	 */
	 getEnterpriseFormData: function(){
	 	var _this = this;
	 	var enterpriseData = $('#enterpriseForm').serialize();
	 	enterpriseData = decodeURIComponent(enterpriseData,true);
	 	enterpriseData = _this.strToObj(enterpriseData);
	 	$("#enterpriseForm input[type='checkbox']").each(function(index,obj){
	 		if(obj.checked){
	 			enterpriseData[obj.name] = 'Y';
	 		}else{
	 			enterpriseData[obj.name] = 'N';
	 		}
	 		//_this.logi(enterpriseData);
	 	});
	 	return enterpriseData;
	 },

	 /**
	 * 暂存网店信息
	 */
	 saveShopFormData: function(){
	 	var _this = this;
	 	var shopData = $('#shopForm').serialize();
	 	shopData = decodeURIComponent(shopData,true);
	 	shopData = _this.strToObj(shopData);
	 	_this.shops.push(shopData);
	 	$("#shopGrid").html($("#shopDataTmpl").render(_this.shops));
	 	$("#shopForm")[0].reset();
	 	$('#choose_sku_modal').modal('hide');
	 },

	 /**
	 * 加载企业详情
	 */

	 loadEnterpriseDetail: function(id){
	 	var _this = this;
	 	$("#enterpriseForm")[0].reset();
	 	$("#enterpriseForm input").each(function(index,el){
	 		$(el).removeAttr('disabled');
	 	});
	 	$("#comments").removeAttr('disabled');
	 	$.ajax({
            type:"POST",
            url:_this.urlItems.queryEnterDetailURL,
            dataType:"json",
            data:{id:id},
            success:function(data){
            	console.log(data);
            	if (data.code != _this.successCode) {
                	window.webDialogUtil.alert("提示","操作失败");
                	return;
                }

                var item = data.result;
                _this.editId = item.id;
                for(var key in item){

 					if($('#'+key)[0] && item.hasOwnProperty(key)){

 						if($('#'+key)[0].tagName == 'TEXTAREA'){
 							$('#'+key).html(item[key]);
 						}else{
 							$('#'+key).attr('value',item[key]);
 						}

 					}
 				}
 				$("#enterpriseForm input[type='checkbox']").each(function(index,el){
 					if(item[el.id] === 'Y'){
 						el.checked = true
 					}else if(item[el.id] === 'N'){
						el.checked = false
 					}
 				});
 				for(var i = 0; i < customerCodes.length; i ++){
 					if(item.customscodetype == customerCodes[i].dictCode){
 						$("#customSelect").val(customerCodes[i].dictName).attr("data-id",customerCodes[i].dictCode);
 						$("#customscodetype").val(customerCodes[i].dictCode);
 					}
 				}
 				_this.loadEnterpriseAttach(id);

 				//_this.initUploadPlugin(item.picPath);
 				_this.queryShoplistByEnterprise(id);
            },
            error: function(){

                window.webDialogUtil.alert("提示","操作失败");
            	_this.loadingDialog.close();
            }
        });



	 },
	 showEnterpriseDetail: function (id){
	 	var _this = this;
	 	_this.loadEnterpriseDetail(id);
	 	$("#enterpriseForm input").each(function(index,el){
	 		$(el).attr('disabled','disabled');
	 	});
	 	$("#comments").attr('disabled','disabled');
	 	_this.loadEnterpriseAttach();
	 },
	 /**
	 * 渲染文件上传框的样式
	 */
	 initUploadPlugin: function (attch){
	 	var _this = this;
	 	var initialPreview = new Array();
	 	if(attch){
	 		initialPreview.push(remoteRes+attch);
	 		$("#fileinput").fileinput('refresh',{
	 			initialPreview: initialPreview
	 		});
	 	}
	 	$("#fileinput").fileinput({
	        showUpload: false,
	        maxFileCount: 1,
	        language : 'zh',
	        showCaption: false,
	        mainClass: "input-group-lg",
	        //allowedFileExtensions: ["jpg", "png", "gif"],
	        initialPreviewAsData: false, // identify if you are sending preview data only and not the raw markup
	        //showPreview:false,
    		showRemove: false,
    		showUpload: false,
    		uploadUrl: _this.urlItems.uploadUrl
	    }).on('fileselect',function(eve, numFiles, label){
	    	var files = $('#fileinput').fileinput('getFileStack');
	    	//验证文件类型
	    	var fileType = files[0].name.split('.');
	    	fileType = fileType[fileType.length-1];
	    	if(fileType != "png" && fileType != "jpg" && fileType != "gif"){
	    		$('#fileinput').fileinput('clear');
	    		window.webDialogUtil.toast({
					type: 'error',
					title: '请选择jpg，png，gif类型的文件'
				});
				return;
	    	};
	    	//验证文件大小
	    	var fileSize = files[0].size;
	    	if(fileSize>204800){
	    		$('#fileinput').fileinput('clear');
	    		window.webDialogUtil.toast({
					type: 'error',
					title: '附件大小不能超过200KB'
				});
				return;
	    	}
	    	/*$('#fileinput').fileinput('refresh',{
	    		uploadExtraData : {
	    			enterpriseId: _this.editId
	    		}
	    	});*/
	    	$(".file-preview").hide();
	    	if(_this.showFlag){
	    		$('#choose_attachtype_modal').modal();
	    	}

	    	//$('#fileinput').fileinput('upload');
	    }).on('fileuploaded',function(event, data, previewId, index){
	    	if(data.response.isSuccess == true){
	    		_this.attachArr.push(data.response.result);
	    		window.webDialogUtil.toast({
					type: 'success',
					title: '上传成功'
				});
	    		_this.fileUploaded(_this.attachArr);
	    		_this.showFlag = true;
	    		_this.attachType = ''
	    		$("#attachMsgForm")[0].reset();
	    		//$('#attachCode').val('');
	    		//$("#attachtypeChoose").bsSuggest('destroy');
	    		//$("#attachtypeChoose").val('');
	    		//dictCtrl.dictionary.load("fileType","attachtype","attachtypeChoose");
	    	}else{
	    		window.webDialogUtil.toast({
					type: 'error',
					title: '上传失败'
				});
	    	}
	    });
	    $(".file-preview").hide();
	 },
	 //上传
	 showFlag: true,
	 doUpload: function(){
	 	if(!_this.attachType){
	 		window.webDialogUtil.toast({
				type: 'error',
				title: '请选择文件类型'
			});
			return ;
	 	}
	 	if(!$('#attachCode').val()){
			window.webDialogUtil.toast({
				type: 'error',
				title: '请输入文件号码'
			});
			return ;
	 	}
	 	$('#choose_attachtype_modal').modal('hide');
	 	$('#fileinput').fileinput('refresh',{
    		uploadExtraData : {
    			enterpiseId: _this.editId,
    			attachtype: _this.attachType,
    			credcode: $('#attachCode').val()
    		}
    	});
    	_this.showFlag = false;
    	$('#fileinput').fileinput('upload');
	 },
	 deleteAttach: function(id){
	 	$.ajax({
            type:"POST",
            url:_this.urlItems.deleteAttachUrl,
            dataType:"json",
            data:{id:id},
            success:function(data){
            	if(data.isSuccess){
			 		for(var i = 0; i < _this.attachArr.length ; i ++){
			 			if(id && _this.attachArr[i].id == id){
			 				_this.attachArr.remove(i);
			 				$("#attachTableBody").html($("#attachDataTmpl").render(_this.attachArr));
			 				//_this.attachArr.remove(i);
			 			}
			 		}
			 	}else{
			 		window.webDialogUtil.toast({
						type: 'error',
						title: '删除失败'
					});
			 	}
            }
        });

	 },
	 fileUploaded: function(arr){
	 	if(arr.length > 0){
	 		for(var i = 0; i < arr.length ; i ++){
	 			var obj = arr[i];
	 			obj.picurl = remoteRes+obj.picturebit;

	 		}
	 		$("#attachTable").show();
	 		$("#attachTableBody").html($("#attachDataTmpl").render(arr));
	 	}
	 },

	 loadEnterpriseAttach: function(enterpriseId){
	 	$.ajax({
            type:"POST",
            url:_this.urlItems.getAttachByEnterUrl,
            dataType:"json",
            data:{id:enterpriseId},
            success:function(data){
            	if(data.result.length>0){
            		$("#attachTable").show();
	 				_this.fileUploaded(data.result);
	 				_this.attachArr = data.result;
            	}
            }
        });
	 },
	 refreshUploadPlugin: function(){
	 	$('#fileinput').fileinput('clear');
	 },
	 enterFormValidate: function(){
		$("#enterpriseForm").validate(enterpriseValidate);
		$("#enterpriseForm").validate();
	 },
	 refreshEnterForm:function(){
	 	$('#filetd').children().remove();
	 	$('#filetd').append('<label class="control-label"></label><input id="fileinput" name="attach" type="file" multiple class="file-loading">');
	 	_this.initUploadPlugin();
	 	$("#enterpriseForm input[type='checkbox']").each(function(index,el){
			el.checked = false
		});
		$("#enterpriseForm input").each(function(index,el){
			//_this.logi(el.name);
			if(el.id=='fileinput'){
				//$('#fileinput').fileinput('clear');
			}else{
				el.value = '';
			}
		});
		$('#comments').html('');
		customscodeUtil.setDefaultCustom("customSelect",pspName);

	 },
	/**
	 * 绑定页面事件
	 */
	event : function(){
		var _this = this;
		$('#showAddStoreDailog').on("click",function(){
			$('#choose_sku_modal').modal();
		});

		$('#saveEnterpriseBtn').on('click',function(){
			_this.submitEnterprise();
		});

		$('#saveShopBtn').on('click',function(){
			_this.saveShopFormData();
		})
		$("#attachtypeChoose").on('onSetSelectValue', function (e, keyword) {
        	_this.attachType = keyword.key;
    	})
    	$("#btnUploadAttach").on('click',function(){
    		_this.doUpload();
    	});
	},

	strToObj: function(str){
	    str = str.replace(/&/g,"','");
	    str = str.replace(/=/g,"':'");
	    str = "({'"+str +"'})";
	    obj = eval(str);
	    return obj;
    }

}

$(function(){
	dictCtrl.dictionary.load("fileType","attachtype","attachtypeChoose");
	enterpriseRecordCtrl.enterpriseRecord.event();
	enterpriseRecordCtrl.enterpriseRecord.initView();
	$('#expired').datetimepicker({
		format: 'yyyy-mm-dd',
        language:  'zh-TW',
        weekStart: 1,
        todayBtn:  1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		minView: 2,
		forceParse: 0
    });
});